package czk.concrent.enjoyModelWithNotLock.atomicRefenceLongAdder.practice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 原子累加器LongAddr的验证
 *
 * @Author:ChenZhangKun
 * @Date: 2021/7/24 19:25
 */
public class LongAdderPractice {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            test(
                    LongAdder::new,
                    LongAdder::increment
            );
        }
    }

    public static <T> void test(Supplier<T> supplier, Consumer<T> consumer) throws InterruptedException {
        // 拿到提供的原子累加器
        T t = supplier.get();
        // 创建集合
        List<Thread> list = new ArrayList<>();
        // 遍历
        for (int i = 0; i < 4; i++) {
            list.add(new Thread(() -> {
                // 每个线程累加50w
                for (int j = 0; j < 500000; j++) {
                    consumer.accept(t);
                }
            }));
        }
        Long start = System.nanoTime();
        // 启动线程
        list.forEach(Thread::start);
        // 等待
        for (Thread thread : list) {
            thread.join();
        }
        //  结束
        Long end = System.nanoTime();
        // 耗时
        System.out.println(t + " cost:" + (end - start) / 1000_000);
    }
}
